package com.itany.interceptor;

import com.itany.ApplicationContextHold;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;


public class LoginInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        StringRedisTemplate template = ApplicationContextHold.getBean(StringRedisTemplate.class);
        boolean flag=false;
        Cookie[] cks = request.getCookies();
        if(null!=cks){
           for(int i=0;i< cks.length;i++){
                Cookie ck = cks[i];
                if("TT_TOKEN".equals(ck.getName())){
                    String token = ck.getValue();
                    String str = template.opsForValue().get("USER_TOKEN::"+token);
                    System.out.println("--------------"+str);
                    flag=true;
                }
           }
        }

        if(!flag){
             StringBuffer httpUrl = request.getRequestURL();
             String url = "http://localhost:9003/user/showlogin?server="
                     + URLEncoder.encode(httpUrl.toString(),"utf-8");

             response.sendRedirect(url);
        }
        return flag;
    }

}
